# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-18 8:22'

from werkzeug.security import check_password_hash, generate_password_hash

from apps.bases.base_mode import BaseMode
from exts import db

class CMSPermission(object):
    #1.拥有所有的权限
    ALL_PERMISSION = 0b11111111
    #2.访问者权限
    VISITOR =        0b00000001
    #3.管理帖子的权限
    POSTER =         0b00000010
    #4.管理评论的权限
    COMMENTER =      0b00000100
    #5.管理板块的权限
    BOARDER  =       0b00001000
    #6.管理前台用户的权限
    FRONTUSER =      0b00010000
    # 7.管理后台用户的权限
    CMSUSER =        0b00100000
    # 8.后台管理员的权限
    ADMINER =        0b01000000

cms_role_user = db.Table('cms_role_user',
                         db.Model.metadata,
                         db.Column('cms_role_id',db.Integer,db.ForeignKey('cms_role.id')),
                         db.Column('cms_user_id',db.Integer,db.ForeignKey('cms_user.id')),
                         primary_key=True)

class CMSRole(BaseMode):
    __tablename__ = 'cms_role'
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),nullable=False)
    desc = db.Column(db.String(200))
    permissions = db.Column(db.Integer, default=CMSPermission.VISITOR)
    users = db.relationship('CMSUser',secondary=cms_role_user,back_populates='roles')

class CMSUser(BaseMode):
    __tablename__ = 'cms_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(50), nullable=False, unique=True)
    _password = db.Column('password', db.String(300), nullable=False)
    nickname = db.Column(db.String(50))
    email = db.Column(db.String(50), nullable=False, unique=True)
    roles = db.relationship('CMSRole',secondary=cms_role_user,back_populates='users')

    def __init__(self, username, password, email,*args,**kwargs):
        self.username = username
        self.password = password
        self.email = email
        BaseMode.__init__(self)


    @property
    def password(self):
        return self._password

    @password.setter
    def password(self, rawpwd):
        self._password = generate_password_hash(rawpwd)

    def check_pwd(self, rawpwd):
        result = check_password_hash(self.password, rawpwd)
        return result

    @property
    def permissions(self):
        if not self.roles:
            return 0
        all_permissions = 0
        for role in self.roles:
            permissions = role.permissions
            all_permissions |= permissions
        return all_permissions

    def has_permission(self,permission):
        return self.permissions&permission == permission

    def is_developer(self):
        return self.has_permission(CMSPermission.ALL_PERMISSION)

